<template>
  <div class="pageContent">
    <!-- 查询条件 -->
    <div class="top flexStartCenter">
      <div class="top-left">
        <div class="aform" style="position:relative">
          <a-form-model
            ref="ruleForm"
            :model="form"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            :rules="rules"
            layout="inline"
          >
            <a-form-model-item ref="selectPro" label="项目" style="width:30%" props="selectPro">
              <a-select
                label-in-value
                :defaultValue="defaultValue"
                @change="handleChange"
                v-if="projectData.length>0 "
              >
                <a-select-option
                  v-for="(item,index) in projectData "
                  :key="index"
                  :value="item.key"
                >{{item.label}}</a-select-option>
              </a-select>
            </a-form-model-item>

            <a-form-model-item label="单位" prop="selectUnit" style="width:30%">
              <a-select v-model="form.selectUnit" label-in-value placeholder="请选择">
                <a-select-option
                  v-for="(item,index) in unit "
                  :key="index"
                  :value="item.key"
                >{{item.label}}</a-select-option>
              </a-select>
            </a-form-model-item>

            <a-form-model-item ref="name" label="姓名" prop="name" style="width:30%" v-if="!fold">
              <a-input placeholder="请输入姓名" v-model="form.name" />
            </a-form-model-item>
            <a-form-model-item
              ref="account"
              label="账号"
              prop="account"
              style="width:30%"
              v-if="!fold"
            >
              <a-input placeholder="请输入账号" v-model="form.account" />
            </a-form-model-item>
            <a-form-model-item v-if="fold" style="width:30%">
              <div class="top-right flexStartCenter" style="margin-left:20px;height:40px">
                <a-button type="primary" style="margin-right:20px" @click="onSearch">查询</a-button>
                <a-button @click="resetForm">重置</a-button>
                <span style="margin-left:20px">
                  <a v-if="fold" style="cursor: pointer" @click="fold=!fold">
                    <span>展开</span>
                    <a-icon type="down" />
                  </a>
                  <a v-else style="cursor: pointer;margin-left:10px" @click="fold=!fold">
                    <span>收起</span>

                    <a-icon type="up" />
                  </a>
                </span>
              </div>
            </a-form-model-item>
          </a-form-model>
        </div>
      </div>
    </div>
    <div class="flexEndCenter" style="height:32px" v-if="!fold">
      <a-button type="primary" style="margin-right:20px" @click="onSearch">查询</a-button>
      <a-button @click="resetForm">重置</a-button>
      <div style="margin-left:10px">
        <a v-if="fold" style="cursor: pointer;margin-left:10px" @click="fold=!fold">
          展开
          <a-icon type="down" />
        </a>
        <a v-else style="cursor: pointer;margin-left:10px" @click="fold=!fold">
          收起
          <a-icon type="up" />
        </a>
      </div>
    </div>
    <!-- 添加和配置 -->
    <div class="add">
      <a-button type="primary" @click="addPeople()" style="margin-right:20px">添加用户</a-button>
      <a-button @click="configRole()">配置角色</a-button>
    </div>
    <!-- 表格选中多少项 -->
    <div style="margin-bottom:20px">
      <a-alert type="info">
        <p slot="description">
          <a-icon type="exclamation-circle" style="color:#1890FF;margin-right:5px" />已选择
          <span style="color:#1890FF;margin:0 5px">{{this.selectedRowKeys.length}}</span>项
        </p>
      </a-alert>
    </div>
    <!-- 中间表格 -->
    <div class="atable">
      <a-table
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :columns="columns"
        :data-source="data"
        :pagination="false"
      >
        <span slot="action" slot-scope="text">
          <a-popconfirm
            title="是否确认删除"
            ok-text="确认"
            cancel-text="取消"
            @confirm="confirm(text)"
            @cancel="cancel"
          >
            <a style="color:#1890FF">删除</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>

    <!-- 分页 -->
    <div class="pagination flexBetween">
      <div>共{{total}} 条记录 第 {{current}} / {{Math.ceil((total/pageSize))}} 页</div>
      <div>
        <a-pagination
          :current="current"
          :page-size-options="pageSizeOptions"
          :total="total"
          show-size-changer
          :page-size="pageSize"
          @showSizeChange="onShowSizeChange"
          @change="pageChange"
          show-quick-jumper
        >
          <template slot="buildOptionText" slot-scope="props">
            <!-- v-if="props.value !== '40'" -->
            <span>{{ props.value }}条/页</span>
            <!-- <span v-if="props.value === '40'">全部</span> -->
          </template>
        </a-pagination>
      </div>
    </div>

    <!-- 对话框 -->
    <div class="amodal_1">
      <a-modal
        v-model="visible"
        :title="modalTitle"
        @ok="handleOk"
        :maskClosable="false"
        cancelText="取消"
        okText="确认"
        width="1000px"
      >
        <div v-if="modalTitle=='添加用户'">
          <a-form-model
            ref="addPeopleForm"
            :model="addPeopleForm"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            :rules="addRules"
            layout="inline"
            v-if="visible"
            style="margin-bottom:10px"
          >
            <a-form-model-item ref="unit" label="单位" style="width:48%" prop="unit">
              <a-select label-in-value :default-value="defaultValueAdd" @change="handleChangeAdd">
                <a-select-option
                  v-for="(item,index) in unit "
                  :key="index"
                  :value="item.key"
                >{{item.label}}</a-select-option>
              </a-select>
            </a-form-model-item>

            <a-form-model-item ref="name" label="姓名" prop="name" style="width:48%;margin-right:0">
              <a-input placeholder="请输入姓名" v-model="addPeopleForm.name" />
            </a-form-model-item>
          </a-form-model>
          <div class="flexCenter" style="margin-bottom:20px">
            <a-button type="primary" style="margin-right:30px" @click="onSearch2">查询</a-button>
            <a-button @click="addResrt">重置</a-button>
          </div>
        </div>

        <div class="atable">
          <a-table
            :row-selection="{ selectedRowKeys: selectedRowKeys2 , onChange: onSelectChange2 }"
            :columns="columnsModal"
            :data-source="dataModal"
            :pagination="false"
          ></a-table>
        </div>

        <!-- 分页 -->
        <div class="pagination flexBetween">
          <div>共{{totalModal}} 条记录 第 {{currentModal}} / {{Math.ceil((totalModal/pageSizeModal))}} 页</div>
          <div>
            <a-pagination
              :current="currentModal"
              :page-size-options="pageSizeOptionsModal"
              :total="totalModal"
              show-size-changer
              :page-size="pageSizeModal"
              @showSizeChange="onShowSizeChangeModal"
              @change="pageChangeModal"
              show-quick-jumper
            >
              <template slot="buildOptionText" slot-scope="props">
                <span>{{ props.value }}条/页</span>
                <!-- <span v-if="props.value !== '40'">{{ props.value }}条/页</span>
                <span v-if="props.value === '40'">全部</span>-->
              </template>
            </a-pagination>
          </div>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script>
import { userQuery, userAdd, userUpdate, userDelete, unitQuery, wxUserQuery, roleQuery, roleAdd } from '@/api/projectUser.js'
import { projectQuery } from '@/api/projectManage'

export default {
  data() {
    return {
      columns: [
        { title: '姓名', dataIndex: 'fullName', key: 'fullName' },
        { title: '账号', dataIndex: 'userName', key: 'userName' },
        { title: '单位', dataIndex: 'tenderCode', key: 'tenderCode', align: 'center' },
        { title: '角色', dataIndex: 'roles', key: 'roles', align: 'center' },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      data: [],
      columnsModal: [
        { title: '姓名', dataIndex: 'fullName', key: 'fullName' },
        { title: '账号', dataIndex: 'userName', key: 'userName' },
        { title: '单位', dataIndex: 'tenderCode', key: 'tenderCode', align: 'center' }
      ],
      dataModal: [],
      selectedRowKeys: [],
      selectedRowKeys2: [],
      selectedRowKeys3: [],
      selectedRows1: [],
      selectedRows2: [],
      form: {
        id: '',
        name: '',
        proName: '',
        proCode: '',
        selectPro: '',
        selectUnit: ''
      },
      form2: {
        name: '',
        account: ''
      },
      addPeopleForm: {
        name: '',
        unit: ''
      },
      defaultValue: {},
      defaultValueAdd: { key: '' },
      likeName: '',
      likeAccount: '',
      visible: false,
      modalTitle: '添加用户',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      pageSizeOptions: ['5', '10', '20', '30', '40'],
      current: 1,
      pageSize: 10,
      total: 1,
      pageSizeOptionsModal: ['5', '10', '20', '30', '40'],
      currentModal: 1,
      pageSizeModal: 5,
      totalModal: 1,
      fold: true,
      projectData: [],
      unit: [],
      rules: {
        selectPro: [{ required: true, message: '请选择项目', trigger: 'change' }],
        selectUnit: [{ required: true, message: '请选择单位', trigger: 'change' }]
      },
      rules2: {
        name: [{ required: true, message: '请输入姓名', trigger: 'change' }],
        account: [{ required: true, message: '请输入账号', trigger: 'change' }]
      },
      addRules: {
        // unit: [
        //   {
        //     required: true,
        //     message: '请选择单位',
        //     trigger: 'change'
        //   }
        // ],
        // name: [{ required: true, message: '请输入姓名', trigger: 'change' }]
      },
      orgId: '',
      projectId: ''
    }
  },
  created() {
    // this.defaultValue = { key: '京沪扩建工程项目' }
    // console.log(this.$route.query.key==undefind);
    if (Object.keys(this.$route.query).length != 0) {
      this.defaultValue = { key: this.$route.query.key }
      this.projectId = this.$route.query.key
      this.getUnit(this.projectId)
    }

    this.projectGet()
    // console.log(this.defaultValue.key);
  },
  mounted() {
    // console.log(this.defaultValue.key);
    this.getTable('')
  },
  // watch: {
  //   projectData: {
  //     handler: function(val, oldval) {
  //       console.log(val);
  //        this.defaultValue = { key: val[0].label }
  //        this.$forceUpdate()
  //     },
  //     deep: true
  //   }
  // },
  methods: {
    onEdit(text) {
      //   console.log(text)
      this.$router.push({ path: '/backManage/projectUserManage' })
    },
    addPeople() {
      // this.selectedRowKeys2 = []
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // console.log(this.form.selectUnit);
          this.orgAddId = this.form.selectUnit.key
          this.selectedRows2 = []
          this.selectedRowKeys2 = []
          this.currentModal=1
          this.modalTitle = '添加用户'
          if (this.form.selectUnit.label) {
            this.defaultValueAdd = { key: this.form.selectUnit.label }
          } else {
            this.defaultValueAdd = { key: '' }
          }
          this.getUserTable()
          this.visible = true
        } else {
          // this.$message.error('请选择单位')
          return false
        }
      })
    },
    onDelete(val) {
      userDelete({ id: val.key }).then((res) => {
        this.$message.success('删除成功')
        this.getTable('')
      })
    },
    confirm(item) {
      // console.log(e);
      this.onDelete(item)
    },
    cancel(e) {
      // console.log(e);
      this.$message.error('取消删除')
    },
    resetForm() {
      // console.log(this.form);
      this.$refs.ruleForm.resetFields()
      // console.log(this.form);
      this.$refs.ruleForm2.resetFields()
    },
    addResrt() {
      this.$refs.addPeopleForm.resetFields()
    },
    configRole() {
      this.selectedRows2 = []
      this.selectedRowKeys2=[]
      // console.log(this.selectedRows1);

      if (this.selectedRows1.length != 0) {
        // if(this.selectedRows1.length==1){
          
          
        //   this.selectedRowKeys2.push(this.selectedRows1[0].key);
        //   // console.log(this.selectedRowKeys2);
        // }
        this.currentModal=1
        this.visible = true
        this.modalTitle = '配置角色'
        this.selectedRowKeys2 = []
        this.getRole()
      } else {
        this.$message.destroy()
        this.$message.error('请选择用户')
      }
    },
    handleOk() {
      // this.$refs.addPeopleForm.validate((valid) => {
      //   if (valid) {
      // console.log(this.selectedRows2.length)
      let data = []
      // console.log(this.selectedRows2)
      if (this.modalTitle != '配置角色') {
        if (this.selectedRows2.length != 0) {
          this.selectedRows2.forEach((item) => {
            let addData = {}
            addData.id = item.key
            addData.fullName = item.fullName
            addData.tel = ''
            addData.userName = item.userName
            addData.orgId = this.orgAddId
            addData.projectId = this.projectId
            data.push(addData)
          })

          userAdd(data).then((res) => {
            this.visible = false
            this.getTable(this.form.selectUnit.key)
          })
          // roleAdd(data).then((res) => {
          //   this.visible = false
          //   this.getTable('')
          // })
        } else {
          this.$message.destroy()
          this.$message.error('请选择用户')
        }
      } else {
        let query = []
        this.selectedRows1.forEach((item, index) => {
          // let roleId=[]
          this.selectedRows2.forEach((val) => {
            let obj = { userId: '', roleId: '' }
            obj.userId = item.id
            obj.roleId = val.id
            query.push(obj)
          })
        })
        roleAdd(query).then((res) => {
          this.$message.success('配置成功')
          this.visible = false
          this.getTable(this.form.selectUnit.key)
        })
      }
      //   } else {
      //     return false
      //   }
      // })
    },
    handleChange(value) {
      // console.log(value)
      this.getUnit(value.key)
      this.form.selectPro = value.label
      this.projectId = value.key
    },
    handleChangeAdd(value) {
      // console.log(value)
      this.orgAddId = value.key
    },
    handleChange2(value) {
      // console.log(this.form.selectUnit)
      this.orgId = value.key
      this.form.selectUnit = value.label
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      // console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows1 = selectedRows
      // console.log(selectedRows)
    },
    onSelectChange2(selectedRowKeys, selectedRows) {
      // console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys2 = selectedRowKeys
      this.selectedRows2 = selectedRows
      // console.log(this.selectedRowKeys2)
      // console.log(selectedRows)
    },
    onShowSizeChange(current, pageSize) {
      // console.log(current, pageSize)
      this.current = 1
      this.pageSize = pageSize
      this.getTable(this.form.selectUnit.key)
    },
    pageChange(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.getTable(this.form.selectUnit.key)
    },
    onShowSizeChangeModal(current, pageSize) {
      // console.log(current, pageSize)
      this.currentModal = 1
      this.pageSizeModal = pageSize
      if (this.modalTitle != '配置角色') {
        this.getUserTable()
      } else {
        this.getRole()
      }
    },
    pageChangeModal(current, pageSize) {
      this.currentModal = current
      this.pageSizeModal = pageSize
      if (this.modalTitle != '配置角色') {
        this.getUserTable()
      } else {
        this.getRole()
      }
    },
    onSearch() {
      // console.log(this.form)

      // console.log(this.form.selectUnit.key);
      // this.$refs.ruleForm.validate((valid) => {
      //   if (valid) {
      this.getTable(this.form.selectUnit.key)
      //   } else {
      //     return false
      //   }
      // })
    },
    onSearch2() {
      // console.log(this.form)

      // console.log(this.form.selectUnit.key);

      this.getUserTable()
    },
    projectGet() {
      let data = {
        page: 0,
        projectId: '',
        size: 0
      }
      this.projectData = []
      projectQuery(data).then((res) => {
        // console.log(res.data.data)
        let data = res.data.data

        data.forEach((item) => {
          item.key = item.id
          item.label = item.name
        })
        this.projectData = data
        if (Object.keys(this.$route.query).length == 0) {
          this.defaultValue = { key: data[0].key }
          this.projectId = this.projectData[0].id
          this.form.id = this.projectData[0].id
          this.getUnit(this.form.id)
          this.form.proName = this.projectData[0].aliasName
          this.form.proCode = this.projectData[0].code
        }

        // this.defaultValue = { key: data[0].key }

        // console.log(data[0].key)
        // this.form.name = this.projectData[0].name

        // this.$forceUpdate()
        // console.log(this.defaultValue);
      })
    },
    getUnit(id) {
      let data = {
        page: 0,
        projectId: id,
        size: 0
      }
      unitQuery(data).then((res) => {
        let data = res.data.data
        // console.log(data)
        data.forEach((item) => {
          item.key = item.id
          item.label = item.name
        })
        this.unit = data
      })
    },
    // 用户查询
    getTable(id) {
      let data = {
        orgId: id,
        page: this.current,
        likeFullName: this.form.name,
        userName: this.form.account,
        projectId: this.projectId,
        size: this.pageSize
      }
      userQuery(data).then((res) => {
        let data = res.data.data
        //  console.log(data);
        data.forEach((item) => {
          item.key = item.id
        })
        this.data = data
        this.total = res.data.total
      })
    },
    // 微信用户查询
    getUserTable() {
      let data = {
        likeFullName: this.addPeopleForm.name,
        orgId: this.orgAddId,
        page: this.currentModal,
        size: this.pageSizeModal
      }
      wxUserQuery(data).then((res) => {
        this.columnsModal = [
          { title: '姓名', dataIndex: 'fullName', key: 'fullName' },
          { title: '账号', dataIndex: 'userName', key: 'userName' },
          { title: '单位', dataIndex: 'tenderCode', key: 'tenderCode', align: 'center' }
        ]
        let data = res.data.data
        //  console.log(res);
        data.forEach((item) => {
          item.key = item.userId
        })
        this.dataModal = data
        // console.log(data);

        this.totalModal = res.data.total
      })
    },
    //获取角色
    getRole() {
      let data = {
        page: this.currentModal,
        size: this.pageSizeModal,
        userIds:this.selectedRowKeys
      }
      this.selectedRowKeys2=[]
      roleQuery(data).then((res) => {
        this.columnsModal = [
          { title: '角色', dataIndex: 'name', key: 'name' },
          { title: '角色说明', dataIndex: 'remarks', key: 'remarks' }
        ]
        let data = res.data.data
        //  console.log(data);
        data.forEach((item) => {
          item.key = item.id
          if(item.selected==1){
            this.selectedRowKeys2.push(item.id)
          }
        })
        this.dataModal = data
        this.totalModal = res.data.total
       
      })
    }
  }
}
</script>

<style scoped>
.top {
  margin-top: 10px;
  width: 100%;
}
.top-left {
  width: 100%;
  /* margin-right: 50px; */
}
.add {
  margin-bottom: 20px;
}
::v-deep .ant-form-inline .ant-form-item {
  margin-bottom: 10px;
}
p {
  margin: 0;
  padding-left: 20px;
}
::v-deep .ant-alert-with-description .ant-alert-message {
  margin-bottom: 0;
}
::v-deep .ant-alert-with-description.ant-alert-no-icon {
  padding: 4px;
}
.atable,
.aform,
.search {
  margin-bottom: 20px;
}
</style>